// *********************************************************
//      Copyright (c) Kosta Gaitanis
//      All rights reserved
//
//      k.gaitanis@gmail.com
//
// *********************************************************

#include "TextureListWidget.h"

TextureListWidget::TextureListWidget(QWidget *parent) :
    CollapsibleWidget(parent),
    m_combo(new QComboBox())
{    
    QWidget *w = new QWidget();
    QVBoxLayout *layout = new QVBoxLayout(w);
    layout->addWidget(m_combo);

    m_combo->addItem("None", QVariant::fromValue<const Texture*>((const Texture*)0));
    connect(m_combo, SIGNAL(currentIndexChanged(int)), this, SLOT(onCurrentIndexChanged(int)));

    setWidget(w);
    setTitle("Textures");
    w->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Fixed);
}

void TextureListWidget::addTexture(const Texture *texture)
{
    QIcon icon(QPixmap::fromImage(texture->getImage()));
    m_combo->addItem(icon, texture->getName(), QVariant::fromValue<const Texture*>(texture));
}

void TextureListWidget::setCurrentTexture(const Texture *texture)
{
    int index = m_combo->findData(QVariant::fromValue<const Texture*>(texture));
    if (index != -1) {
        disconnect(m_combo, SIGNAL(currentIndexChanged(int)), this, SLOT(onCurrentIndexChanged(int)));
        m_combo->setCurrentIndex(index);
        connect(m_combo, SIGNAL(currentIndexChanged(int)), this, SLOT(onCurrentIndexChanged(int)));
    }
}

void TextureListWidget::onCurrentIndexChanged(int index)
{
    Q_UNUSED(index)
    const Texture* texture = getCurrentTexture();
    emit textureChanged(texture);
}

const Texture *TextureListWidget::getCurrentTexture() const
{
    return m_combo->itemData(m_combo->currentIndex()).value<const Texture*>();
}

